﻿package
{
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.utils.Timer;
	import flash.net.*;
	import script.net.SocketRequestEvent;
	import main;
	import User;
	import Hand;
	import DealCards;
	
	public class gameStage extends MovieClip
	{
		public static var rankArr:Array = new Array(
		"3d","3c","3h","3s","4d","4c","4h","4s","5d","5c","5h","5s",
		"6d","6c","6h","6s","7d","7c","7h","7s","8d","8c","8h","8s",
		"9d","9c","9h","9s","0d","0c","0h","0s","Jd","Jc","Jh","Js",
		"Qd","Qc","Qh","Qs","Kd","Kc","Kh","Ks","1d","1c","1h","1s",
		"2d","2c","2h","2s");

		private var myURL:String = "http://chodaidi.ikoaguild.com";
		
		private var isNewPlayer:Array = new Array();
		
		public function gameStage()
		{
			init();
		}

		public function init():void
		{
			var refreshTimer:Timer = new Timer(3000);
			refreshTimer.addEventListener(TimerEvent.TIMER, onTick);
			refreshTimer.start();
			
			this["deal_btn"].buttonMode = true;
			this["deal_btn"].addEventListener(MouseEvent.CLICK, onDealBtnClicked);
			
			this["pass_btn"].buttonMode = true;
			this["pass_btn"].addEventListener(MouseEvent.CLICK, onPassBtnClicked);
			
			this["leave_btn"].buttonMode = true;
			this["leave_btn"].addEventListener(MouseEvent.CLICK, onLeaveClicked);
			for(var i:int; i<4;i++)
			{
				isNewPlayer[i] = true;
			}
			refreshUI();
		}
		
		//dispatch events to start client
		public function onDealBtnClicked(myEvent:MouseEvent):void
		{
			this["output_txt"].text = "";
			this["deal_btn"].enabled = false;
			var mDealCards:DealCards = new DealCards();
			addChild(mDealCards);
			dispatchEvent(new SocketRequestEvent(SocketRequestEvent.CREATE_OBJECT, main.ourGameID,{objectID: "StartGame", properties: main.ourGame.getGameStateXML()}));
		}
		
		public function onPassBtnClicked(myEvent:MouseEvent):void
		{
			this["output_txt"].text = "You have Passed...";
			this["pass_btn"].enabled = false;
			main.ourGame.setStatus(main.ourUserID, "PASS");
			submitGameState();
		}
		
		public function onLeaveClicked(event:MouseEvent)
		{
			goToMain();
		}
		
		//function is called every 3 seconds to reload new UI state
		public function onTick(event:TimerEvent):void 
        {
			gameLogic();
			refreshUI();
		}
		
		// Params: n/a
		// Return: void
		// DESC: The game rules at work
		public function gameLogic():void
		{
			if (main.ourGame.isGameOver() == false)
			{
				this["deal_btn"].enabled = false;
				//Determine if its the local player's turn
				if(main.ourGame.turn == main.ourUserID+1)
				{
					//Checks if the local player has passed for this round or won
					if (main.ourGame.getStatus(main.ourUserID) == "PASSED" ||
						main.ourGame.getStatus(main.ourUserID) == "1ST" || 
						main.ourGame.getStatus(main.ourUserID) == "2ND")
					{
						trace("Passed or Won - Auto - submitGameState");
						submitGameState();
					}
					else
					{
						//User can play or pass
						if(main.ourGame.checkREADY())
						{
							this["output_txt"].text = "PLAY or PASS";
							this["pass_btn"].enabled = true;
						}
						//Everyone else has either passed, won, or disconnected.
						//User can play anything, but cannot pass
						else
						{
							this["output_txt"].text = "Everyone PASSED, Play Anything";
							this["pass_btn"].enabled = false;
							main.ourGame.resetStatus();
						}
					}
				}
				//Not Local Player Turn
				else
				{
					this["output_txt"].text = "Not Our Turn - Do Nothing";
					this["pass_btn"].enabled = false;
				}
			}
			//The Game Over Condition
			else
			{
				this["output_txt"].text = "GAME OVER";
				this["deal_btn"].enabled = true;
				if(main.ourGame.getHand(main.ourUserID) != "")
				{
					main.ourGame.setStatus(main.ourUserID, "4TH");
				}
			}
		}
		
		// Params: n/a
		// Return: void
		// DESC: Sends the new Game State to server.
		public function submitGameState():void
		{
			//check for empty hand
			if(main.ourGame.getHand(main.ourUserID) == "")
			{
				main.ourGame.setStatus(main.ourUserID, main.ourGame.assignRank());
			}
			//next player turn
			main.ourGame.nextTurn();
			//send information to server
			dispatchEvent(new SocketRequestEvent(SocketRequestEvent.CREATE_OBJECT, main.ourGameID,{objectID: "Continuing", properties: main.ourGame.getGameStateXML()}));
		}
		
		// Params: n/a
		// Return: void
		// DESC: Refreshes the UI, such as profile picture and name, on the client's screen
		public function refreshUI():void
		{
			trace ("Turn: "+main.ourGame.turn);
			if(main.loginUser != null)
			{
				for(var i:int=0; i<4; i++)
				{
					if(main.playerArr[i] != null)
					{
						//loads players on gameStage
						if(isNewPlayer[i])
						{
							loadPic(main.playerArr[i].userPic, this["p"+rotate(i)+"_mc"]);
							this["p"+rotate(i)+"name_txt"].text = main.playerArr[i].userName;
							isNewPlayer[i] = false;
						}
					}
					else
					{
						//UNCOMMENT FOR EMPTYSEAT PICTURE
						//loadPic("http://chodaidi.ikoaguild.com/emptyseat.gif", this["p"+rotate(i)+"_mc"]);
						this["p"+rotate(i)+"name_txt"].text = "";
					}
				}
			}
			else
			{
				this["output_txt"].text = "User is NULL!";
			}
		}
		
		// Params: Integer of player position
		// Return: Integer of new position
		// DESC: Adjust the player positions according to local player's position,
		//       so the local player will always be displayed at position '0' with
		//       the other players being 'rotated' reletively. 
		public function rotate(i:int):int
		{
			var iMod:int;
			if(i-main.ourUserID < 0)
			{
				iMod = (i-main.ourUserID)+4;
			}
			else
			{
				iMod = i-main.ourUserID;
			}
			return iMod;
		}
		
		public function loadPic(inURL:String, inTarget:MovieClip):void
		{
			trace("Loading:"+inURL);
			var ldr:Loader = new Loader();
			var url:String = inURL;
			var urlReq:URLRequest = new URLRequest(url);
			ldr.load(urlReq);
			inTarget.addChild(ldr);
        }

		public function goToMain()
		{
			var request:URLRequest = new URLRequest(myURL+"/main.swf");
			var loader:Loader = new Loader()
			loader.load(request);
			addChild(loader);
		}

		// Params: Two Card Strings
		// Return: '1' if card(s) is playable, else '0'
		// DESC: Compares cards lengths to ensure same type.
		//       Redirects card strings to appropriate validation method. 
		public function compareCards(oldCards:String, newCards:String):int
		{
			//check for same hand type
			if(oldCards.length == newCards.length)
			{
				if(newCards.length == 2)
				{
					return singles(oldCards, newCards);
				}
				else if(newCards.length == 4)
				{
					return doubles(oldCards, newCards);
				}
				else if(newCards.length == 6)
				{
					return triples(oldCards, newCards);
				}
				else if(newCards.length == 10)
				{
					return hands(oldCards, newCards);
				}
			}
			else if (newCards.length == 26)
			{
				return dragon(newCards);
			}
			return 0;
		}
		
		// Params: Two Card Strings (length of 2)
		// Return: '1' if card is playable, else '0'
		// DESC: Validates and compares Singles
		public function singles(oldCards:String, newCards:String):int
		{
			if(rankArr.indexOf(oldCards, 0) < rankArr.indexOf(newCards, 0))
			{
				return 1;
			}
			return 0;
		}
		
		// Params: Two Card Strings (length of 4)
		// Return: '1' if pair is playable, else '0'
		// DESC: Validates and compares Pairs
		public function doubles(oldCards:String, newCards:String):int
		{
			if (newCards.charAt(0) == newCards.charAt(2))
			{
				var old_card1:int = rankArr.indexOf(oldCards.charAt(0)+oldCards.charAt(1), 0);
				var old_card2:int = rankArr.indexOf(oldCards.charAt(2)+oldCards.charAt(3), 0);
				var new_card1:int = rankArr.indexOf(newCards.charAt(0)+newCards.charAt(1), 0);
				var new_card2:int = rankArr.indexOf(newCards.charAt(2)+newCards.charAt(3), 0);
	
				if(new_card1 > old_card1 || new_card1 > old_card2 || new_card2 > old_card1 || new_card2 > old_card2)
				{
					return 1;
				}
			}
			return 0;
		}
		
		// Params: Two Card Strings (length of 6)
		// Return: '1' if cards are playable, else '0'
		// DESC: Validates and compares Triples
		public function triples(oldCards:String, newCards:String):int
		{
			if (newCards.charAt(0) == newCards.charAt(2) && newCards.charAt(0) == newCards.charAt(4))
			{
				var old_card:int = rankArr.indexOf(oldCards.charAt(0)+oldCards.charAt(1), 0);
				var new_card:int = rankArr.indexOf(newCards.charAt(0)+newCards.charAt(1), 0);
				
				if(old_card < new_card)
				{
					return 1;
				}
			}
			return 0;
		}
		
		// Params: Two Card Strings (length of 10)
		// Return: '1' if hand is playable, else '0'
		// DESC: Validates and compares Straights, Flushes, etc. Also adds to the user stats count
		public function hands(oldCards:String, newCards:String):int
		{
			var oldHand:Hand = new Hand(oldCards);
			var newHand:Hand = new Hand(newCards);
			
			if(newHand.rank > oldHand.rank)
			{
				//update user stats
				if(newHand.rank > 0 && newHand.rank < 52)
				{ main.loginUser.addST(); }
				else if(newHand.rank > 52 && newHand.rank < 115)
				{ main.loginUser.addFL(); }
				else if(newHand.rank > 115 && newHand.rank < 140)
				{ main.loginUser.addFH(); }
				else if(newHand.rank > 140 && newHand.rank < 155)
				{ main.loginUser.addFK(); }
				else if(newHand.rank > 155)
				{ main.loginUser.addSF(); }

				return 1;
			}
			return 0;
		}
		
		// Params: Card String (length of 26)
		// Return: '1' if cards are playable, else '0'
		// DESC: Checks for the instant win Dragon. Also adds to user stats count.
		public function dragon(newCards:String):int
		{
			var hand:Array = new Array();
			//splits the card string and places it in an array
			for(var i:Number = 0; i<newCards.length; i++)
			{
				hand[i] = newCards.charAt(i);
			}
			//sort hand array for comparison
			hand.sort();
			//create dragon string
			var dhand:String = hand[0]+hand[1]+hand[2]+hand[3]+hand[4]+hand[5]+hand[6]+hand[7]+hand[8]+hand[9]+hand[10]+hand[11]+hand[12];
			//compares dragon string, return result
			if(dhand == "0123456789JKQ")
			{
				//update user stats
				main.loginUser.addDR();
				return 1;
			}
			return 0;
		}
	}
}